﻿using Abp.Domain.Repositories;
using AppFramework.DinosaursParkMes.MaterialModel;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Minio;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AppFramework.DinosaursParkMes
{
    /// <summary>
    /// 公共服务
    /// </summary>
    public class CommonAppService: AppFrameworkAppServiceBase
    {
        private readonly MinioClient _client;
        private readonly IWebHostEnvironment _environment;

        public CommonAppService(MinioClient client, IWebHostEnvironment environment)
        {
            _client = client;
            _environment = environment;
        }
        /// <summary>
        /// 附件上传
        /// </summary>
        /// <param name="files"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpPost, Route("UplodsAsync")]
        public async Task<dynamic> UplodsAsync(List<IFormFile> files)
        {
            string Folder = "";
            //根据name选择的case名称 在minio中生成相应的桶
            for (int i = 0; i < files.Count; i++)
            {

                Folder = "auditattachments";
                //在本项目中添加文件的路径
                var path = $"{_environment.WebRootPath}/img/{DateTime.Now.ToString("yyyyMMdd")}";
                //帮助类进行处理的结果
                var file = files[i];

                var BeBucket = new BucketExistsArgs().WithBucket(Folder);
                //验证桶是否存在
                bool found = await _client.BucketExistsAsync(BeBucket).ConfigureAwait(false);
                //如果桶不存在创建桶
                if (!found)
                {
                    //创建桶
                    var CdBucket = new MakeBucketArgs().WithBucket(Folder);
                    await _client.MakeBucketAsync(CdBucket).ConfigureAwait(false);
                }
                string objectName = file.FileName;//存储的文件名
                                                  //ToDo:通过配置文件获取
                string filePath = $"http://127.0.0.1:9000/{Folder}/{file.FileName}";
                if (file.Length > 0)
                {
                    Stream stream = file.OpenReadStream();
                    var putObjectArgs = new PutObjectArgs().
                    WithBucket(Folder)//minio桶的名称
                    .WithObject(objectName)//上传的文件名称
                                           //.WithFileName(filePath)//文件路径
                    .WithObjectSize(file.Length)
                    .WithStreamData(stream)
                    .WithContentType(files[i].ContentType);//文件类型
                    await _client.PutObjectAsync(putObjectArgs).ConfigureAwait(false);
                }
            }
            return 1;
        }
        /// <summary>
        /// 附件上传
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost, Route("AddFile")]
        public string AddFile(IFormFile file)
        {
            //判断图片是否上传
            if (file == null)
            {
                return "请桑蚕图片";
            }
            //判断图片是否为空
            if (file.Length == 0)
            {
                return "请上传正确的图片";
            }
            //判断文件大小是否符合图片大小
            if (file.Length > 2 * 1024 * 1024)
            {
                return "改文件不符合图片大小";
            }
            //判断是否是图片
            if (!file.ContentType.StartsWith("image/"))
            {
                return "您上传的不是图片";
            }
            var datefile = DateTime.Now.ToString("yyyy-MM-dd");
            if (!Directory.Exists("wwwroot/img/" + datefile))
            {
                Directory.CreateDirectory("wwwroot/img/" + datefile);
            }
            var newname = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName).ToLower();
            var path = "wwwroot/img/" + datefile + "/" + newname;
            using (FileStream fs = new FileStream(path, FileMode.Create))
            {
                file.CopyTo(fs);
                fs.Close();
            }

            return ("http://localhost:44301/img/" + datefile + "/" + newname);
        }
    }
}
